package com.cgsd.heyu.http;


import com.android.library.utils.StringUtils;
import com.google.gson.Gson;
import com.cgsd.heyu.common.Constants;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Description :
 *
 * @Author : shaohua
 * 时间：2019/11/20 17
 * 邮箱：only_dream136@sina.com
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;


    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
        BaseResponse httpResult = gson.fromJson(response, BaseResponse.class);
        if (httpResult.getCode() == Constants.SUCCESS_CODE) {
            String json = jsonStr(response);
            //200的时候就直接解析，不可能出现解析异常。因为我们实体基类中传入的泛型，就是数据成功时候的格式
            return gson.fromJson(json, type);
        } else {
            throw new AnalysisErrorException(httpResult.getCode(), httpResult.getError(), httpResult.getBizBody());
        }
    }

    private String jsonStr(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            String encryptData = jsonObject.optString("bizBody");
            if (StringUtils.isEmpty(encryptData)) {
                jsonObject.put("bizBody", null);
            }
            return jsonObject.toString();
        } catch (Exception e) {
            return response;
        }

    }


}
